<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cookie;
use App\Http\Query\LoginQuery;
use App\Http\Common\Validation;

class LoginController extends Controller
{

    /*
     * ログイン処理
     */
    function doLogin(Request $request)
    {
        $id = $request->input('login_id', '');
        $password = $request->input('password', '');

        $validation = new Validation();
        if (! $validation->isAlnumOrHyphen($id)) {
            session([
                'errorCode' => Config::get('const.errorCode1')
            ]);
            return redirect('login');
        }

        $loginQuery = new LoginQuery();
        $users = $loginQuery->getUserInfoByLoginId($id);

        // TODO: パスワードハッシュ
        if ($users && $users[0] && $users[0]->password !== '' && $users[0]->password === $password && $users[0]->auth && ($users[0]->auth == Config::get('const.authCustomer') || $users[0]->auth == Config::get('const.authAdmin') || $users[0]->auth == Config::get('const.adrojapan'))) {
            Cookie::queue('user_id', $users[0]->user_id, 60 * 24 * 7);
            Cookie::queue('auth', $users[0]->auth, Config::get('const.CookieExpire', 60 * 24 * 7));
            Cookie::queue('user_name', $users[0]->user_name, Config::get('const.CookieExpire', 60 * 24 * 7));

            Cookie::queue('corp_id', $users[0]->corp_id, Config::get('const.CookieExpire', 60 * 24 * 7));
            Cookie::queue('login_id', $users[0]->login_id, Config::get('const.CookieExpire', 60 * 24 * 7));
            Cookie::queue('password', $users[0]->password, Config::get('const.CookieExpire', 60 * 24 * 7));
            Cookie::queue('corp_id', $users[0]->corp_id, Config::get('const.CookieExpire', 60 * 24 * 7));

            if ($users[0]->auth == Config::get('const.authCustomer')) {
                return view('userinstructions');
            } else if ($users[0]->auth == Config::get('const.authAdmin')) {
                return redirect('admin/home');
            } else if ($users[0]->auth == Config::get('const.adrojapan')) {
               return redirect('admin/select_corp');
            }
        } else {
            session([
                'errorCode' => Config::get('const.errorCode1')
            ]);
            return redirect('login');
        }
    }



}
